package com.et.install;

import android.os.RemoteException;

import com.et.install.upgrade.IUpgradeCallBack;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

public final class TaskInstall {

    private static final Executor mInstallThread = Executors.newSingleThreadExecutor();
    private static final AtomicBoolean mBusy = new AtomicBoolean(false);
    private static boolean mIsRoot = false;

    private TaskInstall() {
        mIsRoot = ShellUtil.checkRootPermission();
    }

    private static final class Holder {
        private static final TaskInstall holder = new TaskInstall();
    }

    public static TaskInstall getInstance() {
        return Holder.holder;
    }

    public boolean offerInstallTask(String pkg, String pathName, IUpgradeCallBack callBack) {
        if (!mIsRoot) return false;
        if (mBusy.get()) {
            return false;
        }
        mInstallThread.execute(() -> {
            mBusy.set(true);
            install(pkg, pathName, callBack);
            mBusy.set(false);
        });
        return true;
    }

    private static void install(String pkg, String pathName, IUpgradeCallBack callBack) {
        final String[] cmd = {"pm", "install", "-r", pathName};
        ShellUtil.CommandResult result = ShellUtil.execCommand(cmd, true);
        try {
            callBack.upgradeResult(result.result == 0, pkg, pathName);
        } catch (RemoteException ignored) {
        }
    }
}
